<template>
  <div style="width: 100%; height: 100%;">
    <div id="map" style="width: 100%; height: 100%;"></div>
    <div style="position:absolute;right: 10px;width: 300px;height: 40px;top: 10px;padding:10px;z-index: 999;background-color: white;" v-if="isShowSearch" >
      <!-- 搜索面板 -->
      搜索内容：<input id="keyWord" placeholder="请输入搜索地点" @keyup="handleInput"/>
      <br/>
      <!-- 建议词面板 -->
      <div id="suggestsDiv" class="suggests"  v-if="searchResultList.length > 0" >
        <el-row v-for="result in searchResultList">
          <el-col :span="24" >
            <el-button type="text" @click="handleClickAddress(result)">{{result.name + ' ' + result.address}}</el-button>
          </el-col>
        </el-row>
      </div>
    </div>
    <div style="margin-top: 10px;" v-if="isShowEdit">
      <el-button class="btn" @click="startPoly()" style="margin-bottom: 5px">开始编辑</el-button>
      <el-button class="btn" @click="endPoly()" style="margin-bottom: 5px">结束编辑</el-button>
      <el-button class="btn" @click="clearPoly()">清空</el-button>
    </div>
  </div>
</template>

<script setup name="TiandiTu" lang="ts">
import {transformGCJ02, transformGCJ2WGS} from "@/utils/gisUtil";
import {OssVO} from "@/api/system/oss/types";
import {listByIds} from "@/api/system/oss";

const emit = defineEmits(['update:modelValue', 'pickLngLat', 'finishEdit']);

let map = null;
let handler = null;
let polygon = null;
let polyline = null;
let polygonTool = null;
let localSearch = null;
let geocoder = null;
let markerPoint = null;
let markerTitle = '';
let searchValue= '';
let searchResultList= [];
let markerList= [];
let searchMarker = [];
let pickPointList = [];

const props = defineProps({
  defaultLng: {
    type: Number,
    default: 119.513841,
  },
  defaultLat: {
    type: Number,
    default: 35.43233,
  },
  shapeType: {
    type: String,
    default: "point",
  },
  radiusCircle: {
    type: Number,
    default: 0.00,
  },
  labelTitle:{
    type: String,
    default: "",
  },
  pointList:{
    type: Array,
    default:()=>[],
  },
  fillColor:{
    type: String,
    default: "#FFFFFF",
  },
  zoom: {
    type: Number,
    default: 12,
  },
  isCanPick: {
    type: Boolean,
    default: true,
  },
  isShowCenter: {
    type: Boolean,
    default: true,
  },
  isShowEdit: {
    type: Boolean,
    default: false,
  },
  isShowSearch: {
    type: Boolean,
    default: true,
  },
})

const initMap = () => {
  console.log('window.T',window.T)
  if (window.T) {
    map = new T.Map('map');

    console.log('中心坐标', props.defaultLng, props.defaultLat)
    //level  传参中心点经纬度，以及放大程度，最小1，最大18
    let lng_lat = transformGCJ2WGS(props.defaultLng, props.defaultLat);
    map.centerAndZoom(new T.LngLat(lng_lat.lng, lng_lat.lat), props.zoom); // 设置地图中心点和缩放级别
    map.addControl(new T.Control.Zoom()); // 添加缩放控件
    //允许鼠标双击放大地图
    // map.enableScrollWheelZoom();

    //根据名称进行地址解析 创建对象
    geocoder = new T.Geocoder();


    // 工具
    // var configPolygonTool = {
    //   showLabel: true,
    //   color: "blue", weight: 3, opacity: 0.5, fillColor: props.fillColor, fillOpacity: 0.5
    // };
    // //创建标注工具对象
    // polygonTool = new T.PolygonTool(map, configPolygonTool);
    // polygonTool.addEventListener('draw', drawFinish)  // 监听双击绘制完成事件，调用drawFinish方法

    if(props.isCanPick){
      //拾取经纬度
      var cp = new T.CoordinatePickup(map, {callback: pickLngLat})
      cp.addEvent();
    }

    //创建搜索对象
    var configSearch = {
      pageCapacity: 10,	//每页显示的数量
      onSearchComplete: localSearchResult	//接收数据的回调函数
    };
    localSearch = new T.LocalSearch(map, configSearch);


    //默认加载标注和多边形
    nextTick(()=>{
      if(props.isShowCenter && lng_lat!=undefined){
        //创建标注对象
        markerPoint = new T.Marker(new T.LngLat(lng_lat.lng, lng_lat.lat));
        //向地图上添加标注
        map.addOverLay(markerPoint);

        var latlng = new T.LngLat(lng_lat.lng, lng_lat.lat);
        markerTitle = new T.Label({
          text: props.labelTitle,
          position: latlng,
          offset: new T.Point(-9, 0)
        });
        //创建地图文本对象
        map.addOverLay(markerTitle);
      }

      console.log('props.pointList',props.pointList)

      if(props.shapeType == "point" && props.pointList != undefined && props.pointList.length > 0) {
        var points = [];
        for (let index in props.pointList){

          let lng_lat = transformGCJ2WGS(props.pointList[index].lng, props.pointList[index].lat);
          console.log('lng_lat',lng_lat)
          console.log('new T.LngLat(lng_lat.lng, lng_lat.lat)', new T.LngLat(lng_lat.lng, lng_lat.lat))
          points.push(new T.LngLat(lng_lat.lng, lng_lat.lat));

          //创建标注对象
          //创建图片对象
          var icon = new T.Icon({
            iconUrl: props.pointList[index].icon,//http://api.tianditu.gov.cn/img/map/markerA.png',//require(props.pointList[index].icon),
            iconSize: new T.Point(19, 27),
            iconAnchor: new T.Point(10, 25)
          });

          let marker = new T.Marker(new T.LngLat(lng_lat.lng, lng_lat.lat), { icon : icon } );
          //向地图上添加标注
          map.addOverLay(marker);

          var latlng = new T.LngLat(lng_lat.lng, lng_lat.lat);
          let title = new T.Label({
            text: props.pointList[index].title,
            position: latlng,
            offset: new T.Point(-9, 0)
          });
          //创建地图文本对象
          map.addOverLay(title);

        }
      }
      else if(props.shapeType == "polygon" && props.pointList != undefined && props.pointList.length > 0){
        var points = [];
        for (let index in props.pointList){
          let lng_lat = transformGCJ2WGS(props.pointList[index].lng, props.pointList[index].lat);
          console.log('lng_lat',lng_lat)
          console.log('new T.LngLat(lng_lat.lng, lng_lat.lat)', new T.LngLat(lng_lat.lng, lng_lat.lat))
          points.push(new T.LngLat(lng_lat.lng, lng_lat.lat));
        }
        console.log('points', points)

        //创建面对象
        polygon = new T.Polygon(points, {
          color: "blue", weight: 3, opacity: 0.5, fillColor: props.fillColor, fillOpacity: 0.5
        });
        //向地图上添加面
        map.addOverLay(polygon);
      } else if(props.shapeType == "polyline" && props.pointList != undefined && props.pointList.length > 0){
        var points = [];
        for (let index in props.pointList){
          let lng_lat = transformGCJ2WGS(props.pointList[index].lng, props.pointList[index].lat);
          console.log('lng_lat',lng_lat)
          console.log('new T.LngLat(lng_lat.lng, lng_lat.lat)', new T.LngLat(lng_lat.lng, lng_lat.lat))
          points.push(new T.LngLat(lng_lat.lng, lng_lat.lat));
        }
        console.log('points', points)

        //创建面对象
        polyline = new T.Polyline(points, {
          color: "blue", weight: 3, opacity: 0.5, fillColor: props.fillColor, fillOpacity: 0.5
        });
        //向地图上添加面
        map.addOverLay(polygon);
      } else if(props.shapeType == "circle" && props.radiusCircle != undefined && props.radiusCircle > 0){
        addCircle();
      }
    })
    console.log('地图初始化成功');
  } else {
    console.error('天地图API加载失败');
  }
};

const addCircle = () =>{
  //初始化地图对象
  // map = new T.Map("mapDiv");
  let lng_lat = transformGCJ2WGS(props.defaultLng, props.defaultLat);
  //设置显示地图的中心点和级别
  // map.centerAndZoom(new T.LngLat(lng_lat.lng, lng_lat.lat), props.zoom);
  // 定义该矩形的显示区域  圆的半径，以米点单位。
  var circle = new T.Circle(new T.LngLat(lng_lat.lng, lng_lat.lat), props.radiusCircle,{color:"blue",weight:5,opacity:0.8,fillColor:"#43dede",fillOpacity:0.8,lineStyle:"solid"});
  //向地图上添加圆
  map.addOverLay(circle);
};

const handleClickAddress = (address) => {
  console.log('handleClickAddress', address)
  let lng_lat = address.lonlat.split(',');
  map.centerAndZoom(new T.LngLat(lng_lat[0], lng_lat[1]), props.zoom); // 设置地图中心点和缩放级别
};

const handleInput = () =>{
  let value = document.getElementById('keyWord').value;
  console.log('searchValue', value);
  console.log('searchValue', localSearch);
  if(value!= undefined && value!= '' && localSearch){
    localSearch.search(value, 4)
  }else{
    clearAll();
    searchResultList = []
  }
};

const localSearchResult = (result) => {
  //清空地图及搜索列表
  clearAll();

  //解析建议词信息
  suggests(result.getSuggests());
};

//解析建议词信息
const suggests = (obj) => {
  var that = this;
  if (obj) {
    console.log('suggests', obj);
    setTimeout(function (){
      nextTick(()=> {
        searchResultList = obj;
        for (let index in obj) {
          let address = obj[index];
          if (address.lonlat != undefined && address.lonlat != '') {
            let lng_lat = address.lonlat.split(',');
            //创建标注对象
            var markerTem = new T.Marker(new T.LngLat(lng_lat[0], lng_lat[1]));
            //向地图上添加标注
            map.addOverLay(markerTem);
          }
        }
      });
    }, 300)
  }
};
//清空地图及搜索列表
const clearAll= () => {
  console.log('clearAll', searchMarker)
  map.clearOverLays();
  initMap();
};

const pickLngLat = (lnglat) => {
  // lnglat.lng.toFixed(6) + "," + lnglat.lat.toFixed(6);
  console.log('pickLngLat', lnglat)
  if(markerPoint!= null){
    map.removeOverLay(markerPoint)
  }
  if(markerTitle!= null){
    map.removeOverLay(markerTitle)
  }
  //设置显示地图的中心点和级别
  // map.centerAndZoom(new T.LngLat(lnglat.lng.toFixed(6), lnglat.lat.toFixed(6)), props.zoom);
  markerPoint = new T.Marker(new T.LngLat(lnglat.lng.toFixed(6), lnglat.lat.toFixed(6)));
  map.addOverLay(markerPoint);

  var latlng = new T.LngLat(lnglat.lng.toFixed(6), lnglat.lat.toFixed(6));
  markerTitle = new T.Label({
    text: props.labelTitle,
    position: latlng,
    offset: new T.Point(-9, 0)
  });
  //创建地图文本对象
  map.addOverLay(markerTitle);

  emit('pickLngLat', lnglat);
};
const startPoly= () =>{
  if(polygon != undefined){
    polygon.enableEdit();
  }else{
    console.log('新建多边形')
    if (polygonTool) polygonTool.close();
    var configPolygonTool = {
      showLabel: true,
      color: "blue", weight: 3, opacity: 0.5, fillColor: props.fillColor, fillOpacity: 0.5
    };
    //创建标注工具对象
    polygonTool = new T.PolygonTool(map, configPolygonTool);
    polygonTool.open();
    polygonTool.addEventListener('draw', drawHandle);
  }
};

const drawHandle = (e) => {
  console.log('drawHandle', e)
  // e.currentLnglats
  polygon = e.currentPolygon;
};

const endPoly= () =>{
  if(polygon != undefined){
    polygon.disableEdit();
    console.log('polygon.getLngLats()', polygon.getLngLats()[0])
    let lastPoints = [];
    if(polygon.getLngLats().length > 0){
      for (let index in polygon.getLngLats()[0]){
        let point = polygon.getLngLats()[0][index];
        console.log('point', point)
        let lng_lat = transformGCJ02(point.lng, point.lat);
        let pointNew = {
          lng: lng_lat.lng,
          lat: lng_lat.lat,
        }
        lastPoints.push(pointNew);
      }
      emit('finishEdit', lastPoints);
    }
  }
};
const clearPoly= () =>{
  polygon = null;
  map.clearOverLays();
  pickPointList = [];
};


watch(
  () => props.pointList,
  async (val: Array) => {
    if (val) {
      console.log('watch  pointList', val)

      if(props.shapeType == "point" && props.pointList != undefined && props.pointList.length > 0) {
        var points = [];
        for (let index in props.pointList){

          let lng_lat = transformGCJ2WGS(props.pointList[index].lng, props.pointList[index].lat);
          console.log('lng_lat',lng_lat)
          console.log('new T.LngLat(lng_lat.lng, lng_lat.lat)', new T.LngLat(lng_lat.lng, lng_lat.lat))
          points.push(new T.LngLat(lng_lat.lng, lng_lat.lat));

          //创建标注对象
          //创建图片对象
          var icon = new T.Icon({
            iconUrl: props.pointList[index].icon,//http://api.tianditu.gov.cn/img/map/markerA.png',//require(props.pointList[index].icon),
            iconSize: new T.Point(19, 19),
            iconAnchor: new T.Point(10, 15)
          });

          let marker = new T.Marker(new T.LngLat(lng_lat.lng, lng_lat.lat), { icon : icon } );
          //向地图上添加标注
          map.addOverLay(marker);

          var latlng = new T.LngLat(lng_lat.lng, lng_lat.lat);
          let title = new T.Label({
            text: props.pointList[index].title,
            position: latlng,
            offset: new T.Point(-9, 0)
          });
          //创建地图文本对象
          map.addOverLay(title);

        }
      }
      else if(props.shapeType == "polygon" && props.pointList != undefined && props.pointList.length > 0){
        var points = [];
        for (let index in props.pointList){
          let lng_lat = transformGCJ2WGS(props.pointList[index].lng, props.pointList[index].lat);
          console.log('lng_lat',lng_lat)
          console.log('new T.LngLat(lng_lat.lng, lng_lat.lat)', new T.LngLat(lng_lat.lng, lng_lat.lat))
          points.push(new T.LngLat(lng_lat.lng, lng_lat.lat));
        }
        console.log('points', points)

        //创建面对象
        polygon = new T.Polygon(points, {
          color: "blue", weight: 3, opacity: 0.5, fillColor: props.fillColor, fillOpacity: 0.5
        });
        //向地图上添加面
        map.addOverLay(polygon);
      } else if(props.shapeType == "polyline" && props.pointList != undefined && props.pointList.length > 0){
        var points = [];
        for (let index in props.pointList){
          let lng_lat = transformGCJ2WGS(props.pointList[index].lng, props.pointList[index].lat);
          console.log('lng_lat',lng_lat)
          console.log('new T.LngLat(lng_lat.lng, lng_lat.lat)', new T.LngLat(lng_lat.lng, lng_lat.lat))
          points.push(new T.LngLat(lng_lat.lng, lng_lat.lat));
        }
        console.log('points', points)

        //创建面对象
        polyline = new T.Polyline(points, {
          color: "blue", weight: 3, opacity: 0.5, fillColor: props.fillColor, fillOpacity: 0.5
        });
        //向地图上添加面
        map.addOverLay(polygon);
      } else if(props.shapeType == "circle" && props.radiusCircle != undefined && props.radiusCircle > 0){
        addCircle();
      }

    }
  },
  { deep: true, immediate: true }
);


onMounted(() => {
  initMap();
});

</script>

<style scoped>
#map {
  width: 100%;
  height: 100%;
}
input, b, p {
  margin-left: 5px;
  font-size: 14px
}

/deep/ .tdt-control > div {
  display: none;
}

.search {
  font-size: 13px;
  border: 1px solid #999999;
  line-height: 27px;
  padding-left: 7px;
}

.suggests {
  background-color: white;
  margin: 10px -10px;
  font-size: 13px;
  border: 1px solid #999999;
  padding: 10px;
}


.ls {
  line-height: 27px;
  padding-left: 7px;
}

.prompt {
  background-color: white;
  display: none;
  font-size: 13px;
  border: 1px solid #999999;
}

.statistics {
  background-color: white;
  display: none;
  font-size: 13px;
  border: 1px solid #999999;
  overflow-y: scroll;
  height: 150px;
}


.lineData {
  background-color: white;
  display: none;
  font-size: 13px;
  border: 1px solid #999999;
}

.result {
  background-color: white;
  display: none;
  font-size: 12px;
  border: 1px solid #999999;
  line-height: 27px;
  padding-left: 7px;
}

</style>
